<?php
	session_start();
	include '../templates/php_function.php';
	// Gestion specifique de la session
	if (!isset($_POST))
		header("location: ../../index.php?msg=sessionExpired");

	mysql_connect($_SESSION['BDD_SERVER'], $_SESSION['BDD_LOGIN'], $_SESSION['BDD_PASSWORD']) or die("erreur de connexion au serveur");
	mysql_select_db($_SESSION['BDD']) or die("erreur de connexion a la base de donnees");

	if (!isset($_POST['contexte_id']) || $_POST['contexte_id']=="") {
		$login=$_POST['login'];
		$_SESSION['LOGIN'] = $_POST['login'];
		//Create query
		$qry="SELECT id,nom_complet,dernier_acces, filtre_contexte, filtre_utilisateur FROM utilisateurs WHERE login='$login' AND password='".md5($_POST['password'])."'";
		$result=mysql_query($qry) or die(mysql_error());
		
		//Check whether the query was successful or not
		if ($result) {
			if(mysql_num_rows($result)>0) {
				//Login Successful
				session_regenerate_id();
				$member=mysql_fetch_assoc($result);
				$_SESSION['SESS_MEMBER_NAME']=$member['nom_complet'];
				$_SESSION['SESS_MEMBER_ID']=$member['id'];
				$_SESSION['SESS_FILTRE_CONTEXTE']=$member['filtre_contexte'];
				$_SESSION['SESS_FILTRE_UTILISATEUR']=$member['filtre_utilisateur'];
				$_SESSION['SESS_MEMBER_LASTACCESS']=$member['dernier_acces'];
				$result=mysql_query("UPDATE utilisateurs SET dernier_acces = NOW() WHERE login = '".$login."'") or die(mysql_error());

				session_write_close();
			} else {
				//Login failed
				header("location: ../../index.php?msg=invalidLogin");
				exit();
			}
		} else {
			die("Query failed");
		}
// Degager cette partie et comprendre pourquoi le bordel se met pas en session
/*		
		if($resultContexte) {
			while ($contexte=mysql_fetch_assoc($resultContexte)) {
					$_SESSION['SESS_CONTEXTE_ID']=$contexte['id'];
			}
		}	
		*/
	} else {
		$_SESSION['SESS_CONTEXTE_ID'] = $_POST['contexte_id'];
	}

	$qryContexte="SELECT DISTINCT id,nom_structure FROM role, contexte WHERE utilisateur_id = ".$_SESSION['SESS_MEMBER_ID']." AND role.contexte_id = contexte.id ORDER BY role.defaut DESC ";
	$resultContexte=mysql_query($qryContexte) or die(mysql_error());
	
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
	<?php
	    include '../templates/template_head.php'; 
	?>

	<body>
  		
  		<div id="page">
  		
  			<div id="message">
				<?php
				    include '../templates/template_tableaudebord.php'; 
				?>  			
			</div>
			
			<div id="menu">
				<?php
				    include '../templates/template_menu.php'; 
				?>
			</div>
			
		</div>
	</body>
</html>